// pages/search/index.js
import { searchProduct } from '../../api/index';

Page({
  data: {
    searchKeyword: '',
    hasSearched: false,
    hotKeywords: ['狂飙', '蝴蝶王', '省狂', '国狂', '天极', '红双喜'],
    rubberResults: [],
    bladeResults: [],
    currentFilter: 'all', // 当前筛选类型：all-全部, rubber-胶皮, blade-底板
    filterCount: 0  // 当前筛选后的产品数量。
  },

  onLoad: function(options) {
    const keyword = options.keyword || '';
    this.setData({
      searchKeyword: keyword
    });

    // 如果有传入关键词，直接搜索
    if (keyword) {
      this.doSearch();
    }
  },

  // 输入关键词
  onKeywordInput: function(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
    if(e.detail.value=="") {
      this.setData({
        hasSearched: false
      })
    }
  },

  // 点击热门搜索标签
  onHotTagClick: function(e) {
    const keyword = e.currentTarget.dataset.keyword;
    console.log(keyword)
    this.setData({
      searchKeyword: keyword
    });
    this.doSearch();
  },

  // 切换筛选类型
  onFilterChange: function(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      currentFilter: filter
    });

    let count;
    const { rubberResults, bladeResults } = this.data;
    switch(filter){
      case 'all':
        count = rubberResults.length + bladeResults.length;
        break;
      case 'rubber':
        count = rubberResults.length;
        break;
      case 'blade':
        count = bladeResults.length;
        break;
    }
    this.setData({
      filterCount: count
    })
  },

  // 执行搜索
  doSearch: async function() {
    const keyword = this.data.searchKeyword.trim();
    if ( !keyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }

    if ( keyword < 2) {
      wx.showToast({
        title: '关键词太短',
        icon: 'none'
      });
      return;
    }

    // 显示加载中
    wx.showLoading({
      title: '搜索中...'
    });

    let {result} = await searchProduct(keyword);
    console.log('search ...')
    console.log(result)
    if(result?.count) {
      let {rubberResults, bladeResults} = result.data
      this.setData({
        rubberResults: rubberResults,
        bladeResults: bladeResults,
        hasSearched: true,
        filterCount: result.count
      });
    }
    wx.hideLoading();

    // 模拟搜索API调用
    // setTimeout(() => {
    //   // 这里替换为实际的API调用
    //   const rubberResults = [
    //     {brandName: "红双喜", name: "天弓5"}
    //   ];
    //   const bladeResults = [
    //     {type: "blade", brandName: "红双喜", name: "数字w968"}
    //   ]

    //   let count = rubberResults.length + bladeResults.length;

    //   this.setData({
    //     rubberResults: rubberResults,
    //     bladeResults: bladeResults,
    //     hasSearched: true,
    //     filterCount: count
    //   });

    //   wx.hideLoading();
    // }, 500);
  }

});